﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Globalization;

namespace Pingy.Validators
{
    public class IPValidator : ValidationRule
    {
        public IPVersion IPVersion
        {
            get;
            set;
        }

        List<char> legalChars = new List<char> { '-', '*', '.', ',' }; // Legal chars besides numbers

        public IPValidator()
        {
            IPVersion = IPVersion.IPv4;
        }

        private ValidationResult ValidateIPv4Input(string userInput)
        {
            bool hasIllegalChars = false;
            string illegalChars = "";
            for (int i = 0; i < userInput.Length; i++)
            {
                bool isLegalChar = legalChars.Contains(userInput[i]);
                int value;
                bool isNumber = int.TryParse(userInput[i].ToString(), out value);

                if (!isLegalChar && !isNumber)
                {
                    hasIllegalChars = true;
                    illegalChars += "," + userInput[i];
                }
            }

            if (hasIllegalChars)
            {
                illegalChars = illegalChars.Remove(0, 1); // Remove first instance of ','
                return new ValidationResult(false, "Input contains illegal characters: " + illegalChars);
            }
            else
            {
                return ValidationResult.ValidResult;
            }
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {               
            try
            {
                string userString = value as string;
                switch (IPVersion)
                {
                    case IPVersion.IPv4:
                        return ValidateIPv4Input(userString);
                    case IPVersion.IPv6:
                        return new ValidationResult(false, "IP version 6 is not supported");
                    default:
                        throw new ArgumentOutOfRangeException("Unable to recognize IP version " + IPVersion);
                }
            }
            catch (Exception e)
            {
                return new ValidationResult(false, "Illegal characters or " + e.Message);
            }
        }
    }
}
